package sg.edu.nus.iss;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class Util {
	private static final String DATE_FORMAT_SHORT = "yyyy-MM-dd";
	//private static final String DATE_FORMAT_LONG = "yyyy-MM-dd";
	private static final String DATE_FORMAT_YYMM = "yyyyMM";

	private static DateFormat dfShort = new SimpleDateFormat(DATE_FORMAT_SHORT);
	//private static DateFormat dfLong = new SimpleDateFormat(DATE_FORMAT_LONG);
	private static DateFormat dfYYMM = new SimpleDateFormat(DATE_FORMAT_YYMM);
	
	
	public static boolean isDateValid(int year, int month, int date){
		String yearStr = ""+year;
		String monthStr = (month<10)?"0"+month:""+month;
		String dateStr = (date<10)?"0"+date:""+date;
		String dateString = yearStr +"-"+monthStr+"-"+dateStr;
		return isDateValid(dateString);
	}
	public static boolean isDateValid(String date){
		try{
			dfShort.setLenient(false);
			dfShort.parse(date);
			return true;
		} catch (ParseException e) {
			return false;
		}
	}
	
	public static String oneMonthBackDate(String date)
	{	Date dateObj = null;
	Date backDate = null;
		try{
		dateObj = dfShort.parse(date);
		Calendar cal = Calendar.getInstance();
		cal.setTime(dateObj);
		cal.add(Calendar.MONTH, -1);
		backDate = cal.getTime();
		System.out.println("#### Util : Date = " + dateObj);
		System.out.println("#### Util : BackDate = " + backDate);
		
		}catch (Exception e) {
			return null;
			// TODO: handle exception
		}
		return dfShort.format(backDate);
	}
	
	public static Date parseDate(String dateStr)
	{
		try{
			return dfShort.parse(dateStr);
		}catch(Exception ex)
		{
			return null;
		}

	}

	public static String formatDate(Date date)
	{
		try{
			return dfShort.format(date);
		}catch(Exception ex)
		{
			return null;
		}

	}
	
	public static String getYearMonth(Date date)
	{
		try{
			return dfYYMM.format(date);
		}catch(Exception ex)
		{
			return null;
		}

	}
	
	public static String formatDateFromLong(long longDate) {

		return dfShort.format(longDate);

	}
}
